home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 13203 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.4 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: segmentation fault
  5. Date: 4 Apr 1996 17:19:15 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4k1sejINNc1v@keats.ugrad.cs.ubc.ca>
  8. References: <31636B02.55C6@cts.com> <4k0fjl$ir@ccshst05.cs.uoguelph.ca>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4k0fjl$ir@ccshst05.cs.uoguelph.ca>,
  12. Toby K Hay <thay@uoguelph.ca> wrote:
  13.  >Frank Kragh (kragh@cts.com) wrote:
  14.  >: When running a program, (which didn't yield any errors during compiling), 
  15.  >: I get a "Segmentation fault".  Anybody know what this is and/or what 
  16.  >: might be wrong with my program?
  17.  >
  18.  > I posted this same question here recently and received plenty of 
  19.  >good advice which I'll summarize very briefly.  A segmentation fault 
  20.  >while running a program usually (always?) means that your program is 
  21.  >accessing memory that wasn't allocated to it.  It doesn't happen on a DOS 
  22.  
  23. Not quite. String literals _are_ allocated to the program, yet trying to write
  24. to them (on some systems) causes a segmentation fault.
  25.  
  26.  >machine becuase the OS doesn't do that check - the program can write 
  27.  >wherever it likes, maybe overwriting something vital and crashing the 
  28.  >machine, or maybe not.  On UNIX the OS prevents it and halts the program 
  29.  >with a segmentation fault.  
  30.  > Most people who replied to my question suggested:
  31.  >1) after a call to malloc() check that the returned pointer is not NULL 
  32.  >so that the program doesn't ever try to access memory via a null pointer.
  33.  >2) check that all calls to free() had a valid pointer - no trying to 
  34.  >free() a pointer without a previous call to malloc() or that had already 
  35.  >been free()d.
  36.  >3) check that the program wasn't reading or writing arrays beyond their 
  37.  >declared bounds (e.g. trying to access array elements RA[-1] or RA[7] on 
  38.  >an array declared as int RA[7] whose elements will be numbered 0 to 6).  
  39.  
  40. The latter is unlikely to cause a segmentation fault, because it is likely that
  41. there is valid data adjacent to the array. Protection is usually done to the
  42. granularity of a page, which can be anywhere from 512 bytes to several
  43. kilobytes. On some systems it's possible for a program to protect individual
  44. objects with fine granularity using segmentation, so that's a different story.
  45.  
  46.  >(This was the bug in my program.)
  47.  
  48. You were fortunate that it was caught this way.
  49. -- 
  50.  
  51.